package interfaz;

import clases.ClsDatabase;
import clases.ClsException;
import clases.ClsMetodos;
import clases.*;
import clases.renderIcono;
import java.awt.Color;
import java.awt.Font;


import java.sql.PreparedStatement;
import java.sql.ResultSet;

import java.sql.ResultSetMetaData;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

/**
 *
 * @author SER
 */
public class dlgCronograma extends javax.swing.JDialog {

    private ClsMetodos metodos = new ClsMetodos();
    private ClsDatabase bd = new ClsDatabase();
    ClsRenderAportesLlenada render1 = new ClsRenderAportesLlenada();
    DefaultComboBoxModel modelCboTipoInsumo = new DefaultComboBoxModel();
    DefaultComboBoxModel modelcb1 = new DefaultComboBoxModel();
    DefaultComboBoxModel modelcb2 = new DefaultComboBoxModel();
    DefaultComboBoxModel modelcb3 = new DefaultComboBoxModel();
    String id_proyecto = "1";
    boolean existe = true;
    boolean editable = false;
    String sql_actu_nuevo = "";
    String sql_actu_viejo = "";
    String sql_nuevo = "", sql2_nuevo = "";
    String sql_viejo = "", sql2_viejo = "";
    boolean modifica = false;
    int tap = 1;
    int combo = 1;
//    String idString=null;
    /**
     * Creates new form dlgInsumos2
     *
     * @param parent
     * @param modal
     */
    int c1, c2;

    public dlgCronograma(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        _iniciar();//Iniciamos algunos componentes por defecto...

    }

    public boolean isCellEditable(int row, int cols) {

        if (cols == 0) {
            return false;
        }

        //It will make the cells of Column-1 not Editable

        return true;

    }

    public void modicando(boolean v) {
        modifica = v;
    }

    public dlgCronograma(java.awt.Dialog parent, boolean modal, String id) {
        super(parent, modal);
        initComponents();

        id_proyecto = id;
        _iniciar();//Iniciamos algunos componentes por defecto...
    }
    //___________________________________________________________________________________ Soy una barra separadora :)

    public final void _iniciar() {
        combo = 1;
        setLocationRelativeTo(null);
//        metodos._iconJDialog(this);
        consultas();

        txtBuscar.setText("");
        txtBuscar.requestFocus();
        existencia();
        c1 = 0;
        c2 = 0;

        metodos.comboboxLlenarMas(cboTipoInsumo, modelCboTipoInsumo, "SELECT idinsumo_tipo,nombre FROM insumo_tipo");
//        metodos.comboboxLlenarMas(cboIndice, modelCboIndice, "SELECT idinsumo_indice,concat(idinsumo_indice,'-',descripcion) FROM insumo_indice");

        cargar_instituciones();
        actualizar();

        seleccionar_cargas();

        c1 = 1;
        c2 = 1;
//        tblInsumos.setDefaultRenderer(Object.class, new renderIcono());
        tblInsumos.setDefaultRenderer(Object.class, render1);
        jTable1.setDefaultRenderer(Object.class, new renderIcono());
        alinear_tabla();

        metodos.tablaLongitudColumnas(tblInsumos, new int[]{0, 20, 20, 200, 40, 60, 65, 65, 0, 30, 55, 30, 55, 30, 55, 30});
        metodos.tablaOcultarcolumnas(tblInsumos, new int[]{0, 8});

        metodos.tablaLongitudColumnas(jTable1, new int[]{20, 199, 90, 65, 90, 65, 90, 65, 90, 65, 0});
        metodos.tablaOcultarcolumnas(jTable1, new int[]{10});

//        tblInsumos = new javax.swing.JTable() {
//           
//        };
        //combo_grupo();
//        tblInsumos.getColumnModel().getColumn(9).setCellEditor(new clases.ClsCellEditorAportes(bd, 1, this));
//        tblInsumos.getColumnModel().getColumn(11).setCellEditor(new clases.ClsCellEditorAportes(bd, 1, this));
//        tblInsumos.getColumnModel().getColumn(13).setCellEditor(new clases.ClsCellEditorAportes(bd, 1, this));
        combo = 2;
    }

    public void cargar_instituciones() {
        comboboxLlenar_2(jComboBox1, modelcb1, "SELECT idinstitucion,nombre FROM institucion");
        comboboxLlenar_2(jComboBox2, modelcb2, "SELECT idinstitucion,nombre FROM institucion");
        comboboxLlenar_2(jComboBox3, modelcb3, "SELECT idinstitucion,nombre FROM institucion");
    }

    public void marcar_combos() {
        String sql = "SELECT idinstitucion1, idinstitucion2, idinstitucion3 from contrapartida where idproyecto='" + id_proyecto + "' group by idinstitucion1, idinstitucion2, idinstitucion3;";
//        System.out.println(sql);
        Object data[][] = metodos.cargar_matriz(sql);
        if (data != null) {
            jComboBox1.setSelectedIndex(modelcb1.getIndexOf(data[0][0]));
            jComboBox2.setSelectedIndex(modelcb2.getIndexOf(data[0][1]));
            jComboBox3.setSelectedIndex(modelcb3.getIndexOf(data[0][2]));
        }
    }
    //___________________________________________________________________________________ Soy una barra separadora :)

    public void combo_grupo() {
//        TableColumn sportColumn1 = tblInsumos.getColumnModel().getColumn(9);
//        TableColumn sportColumn2 = tblInsumos.getColumnModel().getColumn(11);
//        TableColumn sportColumn3 = tblInsumos.getColumnModel().getColumn(13);
//        cbgrupo1.removeAllItems();
//        comboboxLlenar(cbgrupo1, modelCboInstitucion, modelnombre, "SELECT idinstitucion,nombre FROM institucion");
//
//        //        cbgrupo1.addItem("Gobierno local");
////        cbgrupo1.addItem("Agua Limpia");
//        sportColumn1.setCellEditor(new DefaultCellEditor(cbgrupo1));
//        sportColumn2.setCellEditor(new DefaultCellEditor(cbgrupo1));
//        sportColumn3.setCellEditor(new DefaultCellEditor(cbgrupo1));
    }

    public void comboboxLlenar(JComboBox cb, DefaultComboBoxModel model, DefaultComboBoxModel modelnombre, String sql) {
        model.removeAllElements();
        cb.removeAllItems();
        try {
            bd.getConnection();
            PreparedStatement pstm = bd.conn.prepareStatement(sql);
            System.out.println("combobox--> " + sql);
            ResultSet res = pstm.executeQuery();
            while (res.next()) {
                model.addElement(res.getString(1));
                String nombre = res.getString(2);
                modelnombre.addElement(nombre);
                cb.addItem(nombre);
            }
            res.close();
        } catch (Exception e) {
            System.err.println(e);
            ClsException._exceptionWriteFile(e, "comboboxLlenar");
        }
        cb.setSelectedIndex(-1);
        cb.setPopupVisible(false);
    }

    public void comboboxLlenar_2(JComboBox cb, DefaultComboBoxModel model, String sql) {
        model.removeAllElements();
        cb.removeAllItems();
        try {
            bd.getConnection();
            PreparedStatement pstm = bd.conn.prepareStatement(sql);
            System.out.println("combobox--> " + sql);
            ResultSet res = pstm.executeQuery();
            while (res.next()) {
                model.addElement(res.getString(1));
                String nombre = res.getString(2);
                cb.addItem(nombre);
            }
            res.close();
        } catch (Exception e) {
            System.err.println(e);
            ClsException._exceptionWriteFile(e, "comboboxLlenar");
        }
        cb.setSelectedIndex(-1);
        cb.setPopupVisible(false);
    }

    public void marcar_nuevo() {
        jComboBox1.setSelectedIndex(1);
        jComboBox2.setSelectedIndex(0);
        jComboBox3.setSelectedIndex(0);
        int n = tblInsumos.getRowCount();
        for (int i = 0; i < n; i++) {

//            String val = "Gobierno Local";
//            tblInsumos.setValueAt(val, i, 9);
            tblInsumos.setValueAt("100", i, 9);
            tblInsumos.setValueAt(tblInsumos.getValueAt(i, 7), i, 10);
//            val = "Sin convenio";
//            tblInsumos.setValueAt(val, i, 11);
            tblInsumos.setValueAt("0", i, 11);
            tblInsumos.setValueAt("0", i, 12);

//            val = "Sin convenio";
//            tblInsumos.setValueAt(val, i, 13);
            tblInsumos.setValueAt("0", i, 13);
            tblInsumos.setValueAt("0", i, 14);
            tblInsumos.setValueAt("100", i, 15);
        }
    }

    public void marcar_tipo_insumo() {
        int n = tblInsumos.getRowCount();
        String cod = modelCboTipoInsumo.getElementAt(cboTipoInsumo.getSelectedIndex()).toString();
        for (int i = 0; i < n; i++) {
            if (tblInsumos.getValueAt(i, 8).toString().equals(cod)) {
                tblInsumos.changeSelection(i, 1, false, false);
                break;
            }
        }
    }

    public void marcar_nombre() {
        int n = tblInsumos.getRowCount();
        String buscado = txtBuscar.getText();
        int l = buscado.length();
        boolean para = false;
        for (int i = 0; i < n; i++) {
            String base = tblInsumos.getValueAt(i, 3).toString();
            if (base.length() >= l) {
                for (int j = 0; j < base.length() - l; j++) {
                    String recorte = base.substring(j, l + j);
                    //System.out.println(recorte);
                    if (recorte.equalsIgnoreCase(buscado)) {
                        tblInsumos.changeSelection(i, 1, false, false);
                        para = true;

                        break;
                    }
                }
            }
            if (para == true) {
                break;
            }
        }
        if (para == false) {
            //tblInsumos.changeSelection(-1, 1, false, false);
            //tblInsumos.getSelectionModel().setSelectionInterval(-1, -1);
        }
    }

    public void marcar_nombreddd() {
        int n = tblInsumos.getRowCount();
        String buscado = txtBuscar.getText();
        int l = buscado.length();
        for (int i = 0; i < n; i++) {
            String base = tblInsumos.getValueAt(i, 3).toString();
            if (base.length() >= l) {
                if (base.substring(0, l).equalsIgnoreCase(buscado)) {
                    tblInsumos.changeSelection(i, 1, false, false);
                    break;
                }
            }
        }
    }

    public void alinear_tabla() {
        //izquierda
        DefaultTableCellRenderer modelocentrar = new DefaultTableCellRenderer();
        modelocentrar.setHorizontalAlignment(SwingConstants.RIGHT);

        DefaultTableCellRenderer modelocentrar_color_1 = new DefaultTableCellRenderer();
        modelocentrar_color_1.setBackground(new java.awt.Color(155, 194, 230));
        modelocentrar_color_1.setHorizontalAlignment(SwingConstants.RIGHT);


        DefaultTableCellRenderer modelocentrar_color_2 = new DefaultTableCellRenderer();
        modelocentrar_color_2.setBackground(new java.awt.Color(192, 80, 77));
        modelocentrar_color_2.setHorizontalAlignment(SwingConstants.RIGHT);


        DefaultTableCellRenderer modelocentrar_color_3 = new DefaultTableCellRenderer();
        modelocentrar_color_3.setBackground(new java.awt.Color(155, 187, 89));
        modelocentrar_color_3.setHorizontalAlignment(SwingConstants.RIGHT);

        tblInsumos.getColumnModel().getColumn(5).setCellRenderer(modelocentrar);
        tblInsumos.getColumnModel().getColumn(6).setCellRenderer(modelocentrar);
        tblInsumos.getColumnModel().getColumn(7).setCellRenderer(modelocentrar);
        tblInsumos.getColumnModel().getColumn(8).setCellRenderer(modelocentrar);
        tblInsumos.getColumnModel().getColumn(9).setCellRenderer(modelocentrar_color_1);
        tblInsumos.getColumnModel().getColumn(10).setCellRenderer(modelocentrar);

        tblInsumos.getColumnModel().getColumn(11).setCellRenderer(modelocentrar_color_2);
        tblInsumos.getColumnModel().getColumn(12).setCellRenderer(modelocentrar);
        tblInsumos.getColumnModel().getColumn(13).setCellRenderer(modelocentrar_color_3);
        tblInsumos.getColumnModel().getColumn(14).setCellRenderer(modelocentrar);
        tblInsumos.getColumnModel().getColumn(15).setCellRenderer(modelocentrar);
        //otra


        jTable1.getColumnModel().getColumn(2).setCellRenderer(modelocentrar);
        jTable1.getColumnModel().getColumn(3).setCellRenderer(modelocentrar);
        jTable1.getColumnModel().getColumn(4).setCellRenderer(modelocentrar);
        jTable1.getColumnModel().getColumn(5).setCellRenderer(modelocentrar);
        jTable1.getColumnModel().getColumn(6).setCellRenderer(modelocentrar);
        jTable1.getColumnModel().getColumn(7).setCellRenderer(modelocentrar);


        DefaultTableCellRenderer modelocentrar4 = new DefaultTableCellRenderer();
        modelocentrar4.setHorizontalAlignment(SwingConstants.RIGHT);
        modelocentrar4.setFont(new Font("Tahoma", Font.BOLD, 15));
        jTable1.getColumnModel().getColumn(8).setCellRenderer(modelocentrar4);
        jTable1.getColumnModel().getColumn(9).setCellRenderer(modelocentrar4);
    }

    public void seleccionar_base(String valor) {
        metodos.seleccionar_tabla(tblInsumos, 0, valor);
    }

    public void existencia() {
        existe = true;
        existe = bd.verif_repite("SELECT idproyecto FROM contrapartida WHERE idproyecto='" + id_proyecto + "'");
    }

    public void seleccionar_cargas() {
        if (!existe) {
            tablaLlenaSql_defecto(tblInsumos, sql_nuevo, sql2_nuevo);
            marcar_nuevo();

        } else {
            tablaLlenaSql_defecto(tblInsumos, sql_viejo, sql2_viejo);
            marcar_combos();
        }
        tablaRedondea(tblInsumos, new int[]{5, 6, 7, 10, 12, 14});
        metodos.tablaNumeracion(tblInsumos, new int[]{1});
        iconos_tipo_insumo(tblInsumos, 8, 2);
        resumen_online();
    }

    public void tablaRedondea(javax.swing.JTable tbl, int columna[]) {
        DefaultTableModel mdt = (DefaultTableModel) tbl.getModel();
        int n = mdt.getRowCount();
        String num;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < columna.length; j++) {
                Object valor = mdt.getValueAt(i, columna[j]);
                if (valor != null) {
                    if (valor.equals("") == false) {
                        //System.out.println(valor);
                        num = metodos.redondeo_1(valor.toString().replace(",", ""));
                        mdt.setValueAt(num, i, columna[j]);
                    } else {
                        mdt.setValueAt("", i, columna[j]);
                    }

                } else {
                    mdt.setValueAt("", i, columna[j]);
                }

            }

        }
    }

    public void consultas() {
        sql_nuevo = " insumo.`idinsumo`,'',insumo_tipo.`idinsumo_tipo` ,insumo.`nombre` ,unidad.`simbolo`,"
                + "sum(partida_detalle.`cantidad`) ,insumo.`precio`,sum(partida_detalle.`precio_parcial`),insumo_tipo.`idinsumo_tipo` "
                + ",'','','','','','',''";
        sql2_nuevo = "FROM "
                + "     `partida_detalle` partida_detalle INNER JOIN `insumo` insumo ON partida_detalle.`idinsumo` = insumo.`idinsumo`\n"
                + "     INNER JOIN `unidad` unidad ON insumo.`idunidad` = unidad.`idunidad`\n"
                + "     INNER JOIN `insumo_tipo` insumo_tipo ON insumo.`idinsumo_tipo` = insumo_tipo.`idinsumo_tipo`\n"
                + "     INNER JOIN `insumo_indice` insumo_indice ON insumo.`idinsumo_indice` = insumo_indice.`idinsumo_indice`\n"
                + "WHERE\n"
                + "     partida_detalle.idproyecto = '" + id_proyecto + "'    "
                + "  "
                + "GROUP BY insumo.`idinsumo`,insumo.`nombre` ,	unidad.`simbolo`,"
                + "insumo.`precio` ,"
                + " insumo_indice.`descripcion`,insumo_tipo.`idinsumo_tipo`"
                + "ORDER BY\n"
                + "     insumo_tipo.`orden` ASC,\n"
                + "     insumo.`nombre` ASC";
        sql_viejo = "      contrapartida.`idinsumo` , '',insumo.`idinsumo_tipo`  ,insumo.`nombre` ,unidad.`simbolo` ,\n"
                + "     contrapartida.`cantidad`,insumo.`precio`,contrapartida.`precio_parcial` ,insumo.`idinsumo_tipo` ,contrapartida.`porcentaje1`,\n"
                + "     institucion.`nombre` ,contrapartida.`porcentaje2` ,institucion_A.`nombre` ,contrapartida.`porcentaje3`,\n"
                + "     institucion_B.`nombre` ,''";
        sql2_viejo = "FROM\n"
                + "     `insumo` insumo INNER JOIN `contrapartida` contrapartida ON insumo.`idinsumo` = contrapartida.`idinsumo`\n"
                + "     INNER JOIN `unidad` unidad ON insumo.`idunidad` = unidad.`idunidad`\n"
                + "     INNER JOIN `insumo_tipo` insumo_tipo ON insumo.`idinsumo_tipo` = insumo_tipo.`idinsumo_tipo`\n"
                + "     INNER JOIN `institucion` institucion ON contrapartida.`idinstitucion1` = institucion.`idinstitucion`\n"
                + "     INNER JOIN `institucion` institucion_A ON contrapartida.`idinstitucion2` = institucion_A.`idinstitucion`\n"
                + "     INNER JOIN `institucion` institucion_B ON contrapartida.`idinstitucion3` = institucion_B.`idinstitucion`\n"
                + "     INNER JOIN `proyecto` proyecto ON contrapartida.`idproyecto` = proyecto.`idproyecto`\n"
                + "WHERE\n"
                + "     contrapartida.idproyecto = '" + id_proyecto + "'\n"
                + "ORDER BY\n"
                + "     insumo_tipo.`orden` ASC,insumo.`nombre` ASC";
//        System.out.println(sql_nuevo + sql2_nuevo);
//        System.out.println(sql_viejo + sql2_viejo);
    }

    public void actualizar() {
        String sql = "";
        //Object data_nueva[][] = metodos.cargar_matriz("select " + sql_nuevo + " " + sql2_nuevo);
        Object data_vieja[][] = metodos.cargar_matriz("select " + sql_viejo + " " + sql2_viejo);
        if (data_vieja != null) {
            if (data_vieja.length != 0) {
                sql = "SELECT idinstitucion1, idinstitucion2, idinstitucion3 from contrapartida where idproyecto='" + id_proyecto + "' group by idinstitucion1, idinstitucion2, idinstitucion3;";
                Object data_instuciones[][] = metodos.cargar_matriz(sql);
                try {
                    bd.getConnection();
                    PreparedStatement pstm = null;
                    //borramos
                    sql = "delete from contrapartida where idproyecto='" + id_proyecto + "'  ";
                    pstm = bd.conn.prepareStatement(sql);
                    pstm.execute();
                    //insertar

                    sql = "insert into contrapartida (idproyecto, idinsumo, cantidad,precio_parcial, porcentaje1, idinstitucion1, porcentaje2, idinstitucion2, porcentaje3, idinstitucion3) "
                            + "SELECT idproyecto ,idinsumo,sum(cantidad),sum(precio_parcial),'100','" + data_instuciones[0][0] + "','0','" + data_instuciones[0][1] + "','0','" + data_instuciones[0][2] + "' FROM partida_detalle where idproyecto = '" + id_proyecto + "' GROUP BY idinsumo;";
                    pstm = bd.conn.prepareStatement(sql);
                    pstm.execute();
                    //actualizar
                    for (int i = 0; i < data_vieja.length; i++) {
                        sql = "update  contrapartida set  porcentaje1='" + data_vieja[i][9] + "',"
                                + " porcentaje2='" + data_vieja[i][11] + "', "
                                + "porcentaje3='" + data_vieja[i][13] + "'  where idproyecto='" + id_proyecto + "' and idinsumo='" + data_vieja[i][0] + "' ";
                        pstm = bd.conn.prepareStatement(sql);
                        pstm.execute();
                    }
                    pstm.close();
                } catch (Exception e) {
                    System.err.println(e);
                    e.printStackTrace();
                    ClsException._exceptionWriteFile(e, "insertando partidas");
                }
            }
        }
    }

    public boolean tablaLlenaSql_defecto(javax.swing.JTable table, String camposSelect, String sqlFromWhere) {
        DefaultTableModel mdt = (DefaultTableModel) table.getModel();
        metodos.tablaLimpia(mdt);
        boolean va = true;
        String sql = "SELECT " + camposSelect + " " + sqlFromWhere;
        int n = 0;
        try {
            bd.getConnection();
            PreparedStatement pstm = bd.conn.prepareStatement(sql);
            ResultSet res = pstm.executeQuery();
            //Previene que en camposSelect tenga: * o concat(   -->para obtener el numero de columnas
//            if (camposSelect.trim().equals("*") || camposSelect.toLowerCase().indexOf("concat(") != -1) {
            ResultSetMetaData rsmd = res.getMetaData();
            n = rsmd.getColumnCount();
//            } else {
//                String colname[] = camposSelect.split(",");
//                n = colname.length;
//            }
//            System.err.println("n-Result-getColumnCount: "+String.valueOf(n));
            while (res.next()) {
                Object mat[] = new Object[n];
                for (int i = 0; i < n; i++) {
                    mat[i] = res.getString(i + 1);
                }
                if (existe) {
                    double cant = Double.parseDouble(mat[7].toString());
                    mat[10] = (cant * Double.parseDouble(mat[9].toString())) / 100;
                    mat[12] = (cant * Double.parseDouble(mat[11].toString())) / 100;
                    mat[14] = (cant * Double.parseDouble(mat[13].toString())) / 100;

                    mat[15] = (int) (Double.parseDouble(mat[9].toString()) + Double.parseDouble(mat[11].toString()) + Double.parseDouble(mat[13].toString()));

                }
                // if (mat[4].toString().equals("%mo") == false) {
                mdt.addRow(mat);
                //}

            }
            res.close();
        } catch (Exception e) {
            System.err.println("sql: " + e);
            e.printStackTrace();
            ClsException._exceptionWriteFile(e, "tablaLlenaSql");
        }

        //System.out.println("tablaLlenaSql--> " + sql);
        return va;
    }

    public boolean validacion() {
        boolean v = true;
        DefaultTableModel mdt = (DefaultTableModel) tblInsumos.getModel();
        int n = mdt.getRowCount();
        for (int i = 0; i < n; i++) {
            if (Double.parseDouble(mdt.getValueAt(i, 15).toString()) != 100) {
                tblInsumos.changeSelection(i, 1, false, false);
                JOptionPane.showMessageDialog(this, "La asignación de porcentajes es incorrecta en: \n" + mdt.getValueAt(i, 3).toString());
                v = false;
                break;
            }
        }
        return v;
    }

    public void grabar() {
        DefaultTableModel mdt = (DefaultTableModel) tblInsumos.getModel();
        int n = mdt.getRowCount();
        if (jComboBox1.getSelectedIndex() != -1 && jComboBox2.getSelectedIndex() != -1 && jComboBox3.getSelectedIndex() != -1) {
            boolean v = true;
            String inst1 = modelcb1.getElementAt(jComboBox1.getSelectedIndex()).toString();
            String inst2 = modelcb2.getElementAt(jComboBox2.getSelectedIndex()).toString();
            String inst3 = modelcb3.getElementAt(jComboBox3.getSelectedIndex()).toString();
            //validacion
            v = validacion();
            if (v == true) {
                bd.delete("contrapartida", "idproyecto='" + id_proyecto + "'");
                //grabar
                for (int i = 0; i < n; i++) {
                    bd.insert("contrapartida", "idproyecto, idinsumo,cantidad,precio_parcial, porcentaje1, idinstitucion1, porcentaje2, idinstitucion2, porcentaje3, idinstitucion3", "'" + id_proyecto + "','" + mdt.getValueAt(i, 0) + "','" + mdt.getValueAt(i, 5) + "','" + mdt.getValueAt(i, 7).toString().replace(",", "") + "','" + mdt.getValueAt(i, 9) + "','" + inst1 + "','" + mdt.getValueAt(i, 11) + "','" + inst2 + "','" + mdt.getValueAt(i, 13) + "','" + inst3 + "' ");
                }
                resumen_online();
                modicando(false);
            }

        } else {
            JOptionPane.showMessageDialog(this, "Seleccione las Instituciones");
        }


    }

    public void calculo_parcial(Object valor, int columna) {
        int fila = tblInsumos.getSelectedRow();
        if (fila != -1) {
            double cant = Double.parseDouble(tblInsumos.getValueAt(fila, 7).toString().replace(",", ""));
            double por = Double.parseDouble(valor.toString());
            double tot = (cant * por) / 100;
            tblInsumos.setValueAt(metodos.redondeo_1(tot), fila, columna);
            double suma = 0;
            if (columna == 10) {
                suma = Double.parseDouble(tblInsumos.getValueAt(fila, 11).toString()) + Double.parseDouble(tblInsumos.getValueAt(fila, 13).toString());
            } else if (columna == 12) {
                suma = Double.parseDouble(tblInsumos.getValueAt(fila, 9).toString()) + Double.parseDouble(tblInsumos.getValueAt(fila, 13).toString());
            } else if (columna == 14) {
                suma = Double.parseDouble(tblInsumos.getValueAt(fila, 11).toString()) + Double.parseDouble(tblInsumos.getValueAt(fila, 9).toString());
            }
            suma = suma + Double.parseDouble(valor.toString());
            tblInsumos.setValueAt((int) suma, fila, 15);
        }

    }

    public void iconos_tipo_insumo(javax.swing.JTable tabla, int col_tipo, int col_asigna) {
        ImageIcon icon1 = new ImageIcon(getClass().getResource("/resource/icon/principales/peque/ico_material_16.png"));
        ImageIcon icon2 = new ImageIcon(getClass().getResource("/resource/icon/principales/peque/ico_obrero.png"));
        ImageIcon icon3 = new ImageIcon(getClass().getResource("/resource/icon/principales/peque/ico_herramienta_12.png"));
        ImageIcon icon4 = new ImageIcon(getClass().getResource("/resource/icon/principales/peque/ico_servicios.png"));
        ImageIcon icon5 = new ImageIcon(getClass().getResource("/resource/icon/principales/peque/vinieta.png"));
        int n = tabla.getRowCount();
        for (int i = 0; i < n; i++) {
            String valor = tabla.getValueAt(i, col_tipo).toString();
            if (valor.equals("1")) {
                tabla.setValueAt(new JLabel(icon1), i, col_asigna);
            } else if (valor.equals("2")) {
                tabla.setValueAt(new JLabel(icon2), i, col_asigna);
            } else if (valor.equals("3")) {
                tabla.setValueAt(new JLabel(icon3), i, col_asigna);
            } else if (valor.equals("4")) {
                tabla.setValueAt(new JLabel(icon4), i, col_asigna);
            } else {
                tabla.setValueAt(new JLabel(icon5), i, col_asigna);
            }
        }
    }
    //___________________________________________________________________________________ Soy una barra separadora :)

    public void reporte(int opcion) {

        if (opcion == 1) {
            //getClass().getResource("/resource/icon/principales/peque/ico_material_16.png")
//            class.getProtectionDomain().getCodeSource().getLocation().getPath();
            System.out.println(getClass().getProtectionDomain().getCodeSource().getLocation().getPath());
//            System.out.println(getClass().getResource("/interfaz/"));
//            System.out.println(getClass().getResource("/resource/icon/principales/peque/ico_material_16.png"));
            metodos.reporte_estandar("contrapartidas.jasper", new String[]{id_proyecto, ""}, "Reporte Contrapartida", 1080, 650);
        } else if (opcion == 2) {

            Object data[][] = resumen_totales();
            if (data != null) {
                if (data.length != 0) {
                    metodos.reporte_estandar("contrapartidas_resumen.jasper", new String[]{id_proyecto, data[0][1].toString(), data[0][2].toString(), data[0][3].toString(), data[0][4].toString(), data[0][5].toString()}, "Reporte Contrapartida", 1080, 650);
                }

            }


            //metodos.reporte_estandar("acu_sub.jasper", new String[]{codigo_proyecto, idpresupuesto}, "Reporte Análisis de costos unitarios", 1080, 650);
        }
    }

    public Object[][] resumen_totales() {
        String sql = "select idproyecto"
                + ",sum(precio_parcial),sum(porcentaje1),sum(porcentaje2),sum(porcentaje3),count(*) "
                + ",sum(precio_parcial)*(sum(porcentaje1)/(100*count(*))),(sum(porcentaje1)/(100*count(porcentaje1)))*100\n"
                + ",sum(precio_parcial)*(sum(porcentaje2)/(100*count(porcentaje2))),(sum(porcentaje2)/(100*count(porcentaje2)))*100\n"
                + ",sum(precio_parcial)*(sum(porcentaje3)/(100*count(porcentaje3))),(sum(porcentaje3)/(100*count(porcentaje3)))*100\n"
                + ",sum(precio_parcial)*(sum(porcentaje1+porcentaje2+porcentaje3)/(100*count(porcentaje1+porcentaje2+porcentaje3)))\n"
                + ",(sum(porcentaje1+porcentaje2+porcentaje3)/(100*count(*)))*100 \n"
                + " from contrapartida "
                + " where idproyecto='" + id_proyecto + "' group by idproyecto;";
        //System.out.println(sql);
        Object obj[][] = metodos.cargar_matriz(sql);
        return obj;
    }

    public void resumen_online() {
        Object data[][] = resumen_totales();
        if (data != null) {
            if (data.length != 0) {

                String sql1 = " i.idinsumo_tipo,ti.nombre\n"
                        + "," + data[0][1] + "*(sum(porcentaje1)/(100*" + data[0][5] + ")),(sum(porcentaje1)/(100*" + data[0][5] + "))*100\n"
                        + "," + data[0][1] + "*(sum(porcentaje2)/(100*" + data[0][5] + ")),(sum(porcentaje2)/(100*" + data[0][5] + "))*100\n"
                        + "," + data[0][1] + "*(sum(porcentaje3)/(100*" + data[0][5] + ")),(sum(porcentaje3)/(100*" + data[0][5] + "))*100\n"
                        + "," + data[0][1] + "*(sum(porcentaje1+porcentaje2+porcentaje3)/(100*" + data[0][5] + "))\n"
                        + ",(sum(porcentaje1+porcentaje2+porcentaje3)/(100*" + data[0][5] + "))*100, i.idinsumo_tipo";
                String sql2 = "from contrapartida cp,insumo i,insumo_tipo ti\n"
                        + "where cp.idinsumo=i.idinsumo and i.idinsumo_tipo=ti.idinsumo_tipo and cp.idproyecto='" + id_proyecto + "'\n"
                        + "group by i.idinsumo_tipo ,ti.nombre "
                        + "order by ti.orden asc;";


                metodos.tablaLlenaSql_defecto(jTable1, sql1, sql2);

//                String sql = "select idproyecto,idproyecto"
//                        + ",sum(cantidad)*(sum(porcentaje1)/(100*count(porcentaje1))),(sum(porcentaje1)/(100*count(porcentaje1)))*100\n"
//                        + ",sum(cantidad)*(sum(porcentaje2)/(100*count(porcentaje2))),(sum(porcentaje2)/(100*count(porcentaje2)))*100\n"
//                        + ",sum(cantidad)*(sum(porcentaje3)/(100*count(porcentaje3))),(sum(porcentaje3)/(100*count(porcentaje3)))*100\n"
//                        + ",sum(cantidad)*(sum(porcentaje1+porcentaje2+porcentaje3)/(100*count(porcentaje1+porcentaje2+porcentaje3)))\n"
//                        + ",(sum(porcentaje1+porcentaje2+porcentaje3)/(100*count(porcentaje1+porcentaje2+porcentaje3)))*100 ,idproyecto  from contrapartida "
//                        + " where idproyecto='" + id_proyecto + "' group by idproyecto;";
//                System.out.println(sql);
//                Object data[][] = metodos.cargar_matriz(sql);
//                if (data != null) {
//                    if (data.length != 0) {
                if (jComboBox1.getSelectedIndex() != -1 && jComboBox2.getSelectedIndex() != -1 && jComboBox3.getSelectedIndex() != -1) {
                    jTextField1.setText(jComboBox1.getSelectedItem().toString());
                    jTextField2.setText(jComboBox2.getSelectedItem().toString());
                    jTextField3.setText(jComboBox3.getSelectedItem().toString());
                }


//                jComboBox1.setSelectedIndex(modelcb1.getIndexOf(data[0][0]));
//                jComboBox2.setSelectedIndex(modelcb2.getIndexOf(data[0][1]));
//                jComboBox3.setSelectedIndex(modelcb3.getIndexOf(data[0][2]));

                DefaultTableModel mdt = (DefaultTableModel) jTable1.getModel();

                Object mat[] = new Object[14];
                mat[0] = "10";
                mat[1] = "Total";
                mat[2] = data[0][6];
                mat[3] = data[0][7];
                mat[4] = data[0][8];
                mat[5] = data[0][9];
                mat[6] = data[0][10];
                mat[7] = data[0][11];
                mat[8] = data[0][12];
                mat[9] = data[0][13];
                mat[10] = "10";


                txt_total_1.setText(mat[1].toString());
                txt_total_2.setText(metodos.redondeo_2(mat[2]));
                txt_total_3.setText(metodos.redondeo_2(mat[3]));
                txt_total_4.setText(metodos.redondeo_2(mat[4]));
                txt_total_5.setText(metodos.redondeo_2(mat[5]));
                txt_total_6.setText(metodos.redondeo_2(mat[6]));
                txt_total_7.setText(metodos.redondeo_2(mat[7]));
                txt_total_8.setText(metodos.redondeo_2(mat[8]));
                txt_total_9.setText(metodos.redondeo_2(mat[9]));
                // mdt.addRow(mat);

//                    }
//                }
                metodos.tablaRedondea(jTable1, new int[]{2, 3, 4, 5, 6, 7, 8, 9});
                iconos_tipo_insumo(jTable1, 10, 0);
//        String[] columNames = {"Codigo", "Nombre", "Apellido", "Edad"};
//        DefaultTableModel datos = new DefaultTableModel();
//        datos.setColumnIdentifiers(columNames);
//        jTable1.setModel(datos);
            }
        }
    }

    public void asigna_texto(JTextField txt_v, JComboBox cb) {
        if (combo == 2) {
            if (cb.getSelectedIndex() != -1) {
                txt_v.setText(cb.getSelectedItem().toString());
            }

        }
    }
//___________________________________________________________________________________ Soy una barra separadora :)

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlInsumos = new javax.swing.JPanel();
        pnlTablaInsumo = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        tblInsumos = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jToolBar2 = new javax.swing.JToolBar();
        btnNuevoCategoria1 = new javax.swing.JButton();
        btnVer = new javax.swing.JButton();
        btnVer1 = new javax.swing.JButton();
        btnEliminarCategoria1 = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jTextField4 = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jTextField6 = new javax.swing.JTextField();
        jTextField3 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jTextField1 = new javax.swing.JTextField();
        txt_total_9 = new javax.swing.JTextField();
        txt_total_8 = new javax.swing.JTextField();
        txt_total_7 = new javax.swing.JTextField();
        txt_total_6 = new javax.swing.JTextField();
        txt_total_3 = new javax.swing.JTextField();
        txt_total_2 = new javax.swing.JTextField();
        txt_total_1 = new javax.swing.JTextField();
        txt_total_4 = new javax.swing.JTextField();
        txt_total_5 = new javax.swing.JTextField();
        jComboBox3 = new javax.swing.JComboBox();
        jComboBox2 = new javax.swing.JComboBox();
        jComboBox1 = new javax.swing.JComboBox();
        btnEliminarCategoria = new javax.swing.JButton();
        txtBuscar = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        cboTipoInsumo = new javax.swing.JComboBox();
        jTextField5 = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Contrapartidas del Proyecto");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        pnlTablaInsumo.setBackground(new java.awt.Color(225, 235, 247));
        pnlTablaInsumo.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        tblInsumos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null}
            },
            new String [] {
                "Cód.", "N°", "", "Descripción", "Unidad", "Cantidad", "P. Unitario", "P. Parcial", "tipo", "%", "(S/.)", "%", "(S/.)", "%", "(S/.)", "Total %"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, true, true, true, false, true, false, true, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblInsumos.setRowHeight(23);
        tblInsumos.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tblInsumos.getTableHeader().setReorderingAllowed(false);
        tblInsumos.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblInsumosMouseClicked(evt);
            }
        });
        jScrollPane3.setViewportView(tblInsumos);

        pnlTablaInsumo.add(jScrollPane3, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 70, 1070, 340));

        jButton1.setForeground(new java.awt.Color(3, 90, 180));
        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/salir.png"))); // NOI18N
        jButton1.setText("Salir");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        pnlTablaInsumo.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(980, 510, 102, -1));

        jToolBar2.setFloatable(false);
        jToolBar2.setRollover(true);
        jToolBar2.setOpaque(false);

        btnNuevoCategoria1.setForeground(new java.awt.Color(3, 90, 180));
        btnNuevoCategoria1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/editar.png"))); // NOI18N
        btnNuevoCategoria1.setText("BD Inst/Org");
        btnNuevoCategoria1.setFocusable(false);
        btnNuevoCategoria1.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnNuevoCategoria1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevoCategoria1ActionPerformed(evt);
            }
        });
        jToolBar2.add(btnNuevoCategoria1);

        btnVer.setForeground(new java.awt.Color(3, 90, 180));
        btnVer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/ver_reporte.png"))); // NOI18N
        btnVer.setText("Reportes");
        btnVer.setFocusable(false);
        btnVer.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnVer.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                btnVerMousePressed(evt);
            }
        });
        btnVer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnVerActionPerformed(evt);
            }
        });
        jToolBar2.add(btnVer);

        btnVer1.setForeground(new java.awt.Color(3, 90, 180));
        btnVer1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/ver_reporte.png"))); // NOI18N
        btnVer1.setText("Resumen");
        btnVer1.setFocusable(false);
        btnVer1.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnVer1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                btnVer1MousePressed(evt);
            }
        });
        btnVer1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnVer1ActionPerformed(evt);
            }
        });
        jToolBar2.add(btnVer1);

        btnEliminarCategoria1.setForeground(new java.awt.Color(3, 90, 180));
        btnEliminarCategoria1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/validacion.png"))); // NOI18N
        btnEliminarCategoria1.setText("Validar");
        btnEliminarCategoria1.setFocusable(false);
        btnEliminarCategoria1.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnEliminarCategoria1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarCategoria1ActionPerformed(evt);
            }
        });
        jToolBar2.add(btnEliminarCategoria1);

        pnlTablaInsumo.add(jToolBar2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1090, -1));

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jPanel2.setOpaque(false);
        jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "", "Rubro", "(S/.)", "(%)", "(S/.)", "(%)", "(S/.)", "(%)", "(S/.)", "(%)", "icono"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        jTable1.setRowHeight(20);
        jTable1.getTableHeader().setResizingAllowed(false);
        jTable1.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(jTable1);

        jPanel2.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(5, 20, 845, 110));

        jTextField4.setEditable(false);
        jTextField4.setBackground(new java.awt.Color(255, 204, 51));
        jTextField4.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jTextField4.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jTextField4.setText("Total");
        jTextField4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField4ActionPerformed(evt);
            }
        });
        jPanel2.add(jTextField4, new org.netbeans.lib.awtextra.AbsoluteConstraints(691, 0, 160, -1));

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel3.setText("RESUMEN");
        jPanel2.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 0, 80, 20));

        jTextField6.setEditable(false);
        jTextField6.setBackground(new java.awt.Color(255, 204, 51));
        jTextField6.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jTextField6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField6ActionPerformed(evt);
            }
        });
        jPanel2.add(jTextField6, new org.netbeans.lib.awtextra.AbsoluteConstraints(5, 0, 223, -1));

        jTextField3.setEditable(false);
        jTextField3.setBackground(new java.awt.Color(146, 195, 252));
        jTextField3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jTextField3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField3ActionPerformed(evt);
            }
        });
        jPanel2.add(jTextField3, new org.netbeans.lib.awtextra.AbsoluteConstraints(536, 0, 159, -1));

        jTextField2.setEditable(false);
        jTextField2.setBackground(new java.awt.Color(146, 195, 252));
        jTextField2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jTextField2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField2ActionPerformed(evt);
            }
        });
        jPanel2.add(jTextField2, new org.netbeans.lib.awtextra.AbsoluteConstraints(380, 0, 160, -1));

        jTextField1.setEditable(false);
        jTextField1.setBackground(new java.awt.Color(146, 195, 252));
        jTextField1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });
        jPanel2.add(jTextField1, new org.netbeans.lib.awtextra.AbsoluteConstraints(224, 0, 160, -1));

        txt_total_9.setEditable(false);
        txt_total_9.setBackground(new java.awt.Color(255, 204, 0));
        txt_total_9.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        txt_total_9.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        jPanel2.add(txt_total_9, new org.netbeans.lib.awtextra.AbsoluteConstraints(780, 125, 70, -1));

        txt_total_8.setEditable(false);
        txt_total_8.setBackground(new java.awt.Color(255, 204, 0));
        txt_total_8.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        txt_total_8.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        jPanel2.add(txt_total_8, new org.netbeans.lib.awtextra.AbsoluteConstraints(690, 125, 94, -1));

        txt_total_7.setEditable(false);
        txt_total_7.setBackground(new java.awt.Color(146, 195, 252));
        txt_total_7.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        txt_total_7.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        jPanel2.add(txt_total_7, new org.netbeans.lib.awtextra.AbsoluteConstraints(625, 125, 69, -1));

        txt_total_6.setEditable(false);
        txt_total_6.setBackground(new java.awt.Color(146, 195, 252));
        txt_total_6.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        txt_total_6.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        jPanel2.add(txt_total_6, new org.netbeans.lib.awtextra.AbsoluteConstraints(535, 125, 94, -1));

        txt_total_3.setEditable(false);
        txt_total_3.setBackground(new java.awt.Color(146, 195, 252));
        txt_total_3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        txt_total_3.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        jPanel2.add(txt_total_3, new org.netbeans.lib.awtextra.AbsoluteConstraints(315, 125, 69, -1));

        txt_total_2.setEditable(false);
        txt_total_2.setBackground(new java.awt.Color(146, 195, 252));
        txt_total_2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        txt_total_2.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        jPanel2.add(txt_total_2, new org.netbeans.lib.awtextra.AbsoluteConstraints(224, 125, 95, -1));

        txt_total_1.setEditable(false);
        txt_total_1.setBackground(new java.awt.Color(255, 204, 51));
        txt_total_1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        txt_total_1.setText("TOTAL");
        jPanel2.add(txt_total_1, new org.netbeans.lib.awtextra.AbsoluteConstraints(5, 125, 223, -1));

        txt_total_4.setEditable(false);
        txt_total_4.setBackground(new java.awt.Color(146, 195, 252));
        txt_total_4.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        txt_total_4.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        jPanel2.add(txt_total_4, new org.netbeans.lib.awtextra.AbsoluteConstraints(380, 125, 94, -1));

        txt_total_5.setEditable(false);
        txt_total_5.setBackground(new java.awt.Color(146, 195, 252));
        txt_total_5.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        txt_total_5.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        jPanel2.add(txt_total_5, new org.netbeans.lib.awtextra.AbsoluteConstraints(470, 125, 69, -1));

        pnlTablaInsumo.add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 420, 855, 160));

        jComboBox3.setBackground(new java.awt.Color(78, 105, 22));
        jComboBox3.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        jComboBox3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox3ActionPerformed(evt);
            }
        });
        pnlTablaInsumo.add(jComboBox3, new org.netbeans.lib.awtextra.AbsoluteConstraints(880, 40, 130, -1));

        jComboBox2.setBackground(new java.awt.Color(255, 0, 0));
        jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        jComboBox2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox2ActionPerformed(evt);
            }
        });
        pnlTablaInsumo.add(jComboBox2, new org.netbeans.lib.awtextra.AbsoluteConstraints(750, 40, 130, -1));

        jComboBox1.setBackground(new java.awt.Color(26, 95, 146));
        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });
        pnlTablaInsumo.add(jComboBox1, new org.netbeans.lib.awtextra.AbsoluteConstraints(620, 40, 130, -1));

        btnEliminarCategoria.setForeground(new java.awt.Color(3, 90, 180));
        btnEliminarCategoria.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/guardar.png"))); // NOI18N
        btnEliminarCategoria.setText("Guardar");
        btnEliminarCategoria.setFocusable(false);
        btnEliminarCategoria.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnEliminarCategoria.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarCategoriaActionPerformed(evt);
            }
        });
        pnlTablaInsumo.add(btnEliminarCategoria, new org.netbeans.lib.awtextra.AbsoluteConstraints(980, 460, 100, 35));

        txtBuscar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtBuscarKeyReleased(evt);
            }
        });
        pnlTablaInsumo.add(txtBuscar, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 40, 270, -1));

        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Buscar:");
        pnlTablaInsumo.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 40, -1, 25));

        jLabel9.setText("Tipo insumo:");
        pnlTablaInsumo.add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 40, -1, 25));

        cboTipoInsumo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cboTipoInsumo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cboTipoInsumoActionPerformed(evt);
            }
        });
        pnlTablaInsumo.add(cboTipoInsumo, new org.netbeans.lib.awtextra.AbsoluteConstraints(430, 40, 170, -1));

        jTextField5.setEditable(false);
        jTextField5.setBackground(new java.awt.Color(204, 225, 249));
        jTextField5.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jTextField5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField5ActionPerformed(evt);
            }
        });
        pnlTablaInsumo.add(jTextField5, new org.netbeans.lib.awtextra.AbsoluteConstraints(610, 35, 470, 40));

        jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/fondo_dialog.jpg"))); // NOI18N
        pnlTablaInsumo.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 450, 330));

        javax.swing.GroupLayout pnlInsumosLayout = new javax.swing.GroupLayout(pnlInsumos);
        pnlInsumos.setLayout(pnlInsumosLayout);
        pnlInsumosLayout.setHorizontalGroup(
            pnlInsumosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlTablaInsumo, javax.swing.GroupLayout.DEFAULT_SIZE, 1093, Short.MAX_VALUE)
        );
        pnlInsumosLayout.setVerticalGroup(
            pnlInsumosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlTablaInsumo, javax.swing.GroupLayout.DEFAULT_SIZE, 584, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlInsumos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlInsumos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tblInsumosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblInsumosMouseClicked

        if (tblInsumos.getSelectedRow() == 2 & tblInsumos.getSelectedColumn() == 8) {
            editable = true;
        } else {
            editable = false;
        }

    }//GEN-LAST:event_tblInsumosMouseClicked

    private void txtBuscarKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBuscarKeyReleased
        marcar_nombre();
    }//GEN-LAST:event_txtBuscarKeyReleased

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if (modifica == true) {
            if (javax.swing.JOptionPane.showConfirmDialog(null, "¿Desea guardar los cambios efectuados?", "Mensaje", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == 0) {
                grabar();
            } else {
                dispose();
            }
        } else {
            dispose();
        }


    }//GEN-LAST:event_jButton1ActionPerformed

    private void cboTipoInsumoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cboTipoInsumoActionPerformed
        if (c1 == 1) {
            marcar_tipo_insumo();
        }
    }//GEN-LAST:event_cboTipoInsumoActionPerformed

    private void btnNuevoCategoria1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoCategoria1ActionPerformed
        dlgInstitucion dialog = new dlgInstitucion(this, true);
        dialog.setVisible(true);
        int b1 = jComboBox1.getSelectedIndex();
        int b2 = jComboBox2.getSelectedIndex();
        int b3 = jComboBox3.getSelectedIndex();
        cargar_instituciones();
        if (b1 < jComboBox1.getItemCount()) {
            jComboBox1.setSelectedIndex(b1);
        }
        if (b2 < jComboBox2.getItemCount()) {
            jComboBox2.setSelectedIndex(b2);
        }
        if (b3 < jComboBox3.getItemCount()) {
            jComboBox3.setSelectedIndex(b3);
        }



    }//GEN-LAST:event_btnNuevoCategoria1ActionPerformed

    private void btnEliminarCategoriaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarCategoriaActionPerformed
        grabar();
    }//GEN-LAST:event_btnEliminarCategoriaActionPerformed

    private void btnVerMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnVerMousePressed
//        menuPresupuesto.show(evt.getComponent(), 0, 30);
    }//GEN-LAST:event_btnVerMousePressed

    private void btnVerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVerActionPerformed
        reporte(1);
    }//GEN-LAST:event_btnVerActionPerformed

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField1ActionPerformed

    private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField2ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField2ActionPerformed

    private void jTextField3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField3ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField3ActionPerformed

    private void jTextField4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField4ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField4ActionPerformed

    private void jTextField5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField5ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField5ActionPerformed

    private void btnVer1MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnVer1MousePressed
        // TODO add your handling code here:
    }//GEN-LAST:event_btnVer1MousePressed

    private void btnVer1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVer1ActionPerformed
        reporte(2);
    }//GEN-LAST:event_btnVer1ActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        if (modifica == true) {
            if (javax.swing.JOptionPane.showConfirmDialog(null, "¿Desea guardar los cambios efectuados?", "Mensaje", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == 0) {
                // setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
                grabar();
//                return;
            } else {
                dispose();
            }
        } else {
            dispose();
        }
    }//GEN-LAST:event_formWindowClosing

    private void btnEliminarCategoria1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarCategoria1ActionPerformed
        if (validacion()) {
            JOptionPane.showMessageDialog(this, "La validación fue correcta");
        }
    }//GEN-LAST:event_btnEliminarCategoria1ActionPerformed

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
        asigna_texto(jTextField1, jComboBox1);
    }//GEN-LAST:event_jComboBox1ActionPerformed

    private void jComboBox2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox2ActionPerformed
        asigna_texto(jTextField2, jComboBox2);
    }//GEN-LAST:event_jComboBox2ActionPerformed

    private void jComboBox3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox3ActionPerformed
        asigna_texto(jTextField3, jComboBox3);
    }//GEN-LAST:event_jComboBox3ActionPerformed

    private void jTextField6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField6ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField6ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(dlgCronograma.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(dlgCronograma.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(dlgCronograma.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(dlgCronograma.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the dialog
         */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                dlgCronograma dialog = new dlgCronograma(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnEliminarCategoria;
    private javax.swing.JButton btnEliminarCategoria1;
    private javax.swing.JButton btnNuevoCategoria1;
    private javax.swing.JButton btnVer;
    private javax.swing.JButton btnVer1;
    private javax.swing.JComboBox cboTipoInsumo;
    private javax.swing.JButton jButton1;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JComboBox jComboBox2;
    private javax.swing.JComboBox jComboBox3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    private javax.swing.JTextField jTextField6;
    private javax.swing.JToolBar jToolBar2;
    public javax.swing.JPanel pnlInsumos;
    private javax.swing.JPanel pnlTablaInsumo;
    private javax.swing.JTable tblInsumos;
    private javax.swing.JTextField txtBuscar;
    private javax.swing.JTextField txt_total_1;
    private javax.swing.JTextField txt_total_2;
    private javax.swing.JTextField txt_total_3;
    private javax.swing.JTextField txt_total_4;
    private javax.swing.JTextField txt_total_5;
    private javax.swing.JTextField txt_total_6;
    private javax.swing.JTextField txt_total_7;
    private javax.swing.JTextField txt_total_8;
    private javax.swing.JTextField txt_total_9;
    // End of variables declaration//GEN-END:variables
}
